var fs = require('fs')
var path = require('path')
var http = require('http')
var querystring = require('querystring')
var url = require('url')

var documentRoot = path.resolve(__dirname)

var server = http.createServer()

server.on('request', function (req, res) {
  var file_path = ''

  // parses the url request for a file and pulls the pathname
  var url_request = url.parse(req.url).pathname
  var tmp = url_request.lastIndexOf('.')
  var extension = url_request.substring(tmp + 1)

  file_path = url_request.replace('/', '')

  //load needed pages and static files
  fs.readFile(file_path, function (error, contents) {
    if (error) {
      console.log('DIE!');
      console.log(error);
      res.writeHeader(500, { 'Content-Type': 'text/html' });
      res.end('<h1>FS READ FILE ERROR: Internal Server Error!</h1>');
    } else {
      console.log('SUCCESS!');
      // set content type
      switch (extension) {
        case 'html':
        case 'htm':
          res.writeHeader(200, { 'Content-Type': 'text/html' });
          break;
        case 'css':
          res.writeHeader(200, { 'Content-Type': 'text/css' });
          break;
        case 'js':
          res.writeHeader(200, { 'Content-Type': 'text/javascript' });
          break;
        case 'png':
          res.writeHeader(200, { 'Content-Type': 'image/png' });
          break;
        case 'jpg':
        case 'jpeg':
          res.writeHeader(200, { 'Content-Type': 'image/jpg' });
          break;
        case 'svg':
          res.writeHeader(200, { 'Content-Type': 'image/svg+xml' });
          break;
        default:
          console.log('NO CORRECT EXTENSION');
          break;
      }

      console.log(extension);
      res.end(contents);
    }
  })
})

server.listen(3000, function (err) {
  if (!err) {
    console.log('server is running on port 3000')
  }
})


